package com.bsbm.member.dao.impl;

import com.bsbm.member.bean.MemberBean;
import com.bsbm.member.dao.MemberDao;
import com.bsbm.member.domain.Member;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * Created by SABIR IQBAL on 3/23/14.
 */
public class MemberDaoImpl extends HibernateDaoSupport implements MemberDao{
    @Override
    public void create(Member member) {
        getHibernateTemplate().save(member);
    }

    @Override
    public Member findById(Long id) {
        List<Member> members=  getHibernateTemplate().find("from Member where id="+id);
        return CollectionUtils.isEmpty(members)? null : members.get(0);
    }

    @Override
    public List<Member> search(MemberBean memberBean) {
        StringBuffer query = new StringBuffer("from Member where ");
        if(StringUtils.hasText(memberBean.getFirstName())) {
            query.append(" firstName ='"+memberBean.getFirstName()+"' ");
        }
        if(StringUtils.hasText(memberBean.getMiddleName())) {
            if(StringUtils.hasText(memberBean.getFirstName())) {
                query.append(" and ");
            }
            query.append(" middleName ='"+memberBean.getMiddleName()+"' ");
        }
        if(StringUtils.hasText(memberBean.getLastName())) {
            if(StringUtils.hasText(memberBean.getFirstName()) || StringUtils.hasText(memberBean.getMiddleName())) {
                query.append(" and ");
            }
            query.append(" lastName ='"+memberBean.getLastName()+"' ");
        }
        if(StringUtils.hasText(memberBean.getIdCardNo())) {
            if(StringUtils.hasText(memberBean.getFirstName()) || StringUtils.hasText(memberBean.getMiddleName())
                    || StringUtils.hasText(memberBean.getLastName())) {
                query.append(" and ");
            }
            query.append(" idCardNo ='"+memberBean.getIdCardNo()+"' ");
        }
        if(StringUtils.hasText(memberBean.getFormNo())) {
            if(StringUtils.hasText(memberBean.getFirstName()) || StringUtils.hasText(memberBean.getMiddleName())
                    || StringUtils.hasText(memberBean.getLastName()) || StringUtils.hasText(memberBean.getIdCardNo())) {
                query.append(" and ");
            }
            query.append(" formNo ='"+memberBean.getFormNo()+"'");
        }

        List<Member> members = getHibernateTemplate().find(query.toString());
        return members;
    }

    @Override
    public void delete(Long userId) {
        getHibernateTemplate().delete(findById(userId));
    }

}
